package cn.wolfcode.web.advice;
import cn.wolfcode.exception.BusinessException;
import cn.wolfcode.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


//统一异常处理

//标记该类为Controller的增强类
@ControllerAdvice
public class ExceptionControllerAdvice {
    //表示处理什么类型的异常
    @ExceptionHandler(BusinessException.class)
    public void handlerBusinessException(BusinessException e, HttpServletResponse response, HandlerMethod handlerMethod) throws IOException {
        e.printStackTrace();
        ResponseBody methodAnnotation = handlerMethod.getMethodAnnotation(ResponseBody.class);
        if (methodAnnotation==null){
            //访问页面
            response.sendRedirect("/error");
        }else{
            //JSON数据的请求
            response.setContentType("application/json;charset=utf-8");  //处理乱码问题
            String responseData = JSON.toJSONString(new JsonResult(false, e.getMessage()));
            response.getWriter().write(responseData);
        }
    }

    @ExceptionHandler(Exception.class)
    public void handlerException(Exception e, HttpServletResponse response, HandlerMethod handlerMethod) throws IOException {
        e.printStackTrace();
        ResponseBody methodAnnotation = handlerMethod.getMethodAnnotation(ResponseBody.class);
        if (methodAnnotation==null){
            //访问页面
            response.sendRedirect("/error");
        }else{
            //JSON数据的请求
            response.setContentType("application/json;charset=utf-8");  //处理乱码问题
            String responseData = JSON.toJSONString(new JsonResult(false, "系统异常，请联系管理员"));
            response.getWriter().write(responseData);
        }
    }
}
